package org.example;

import org.junit.Test;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Java21ToVirtualThreadMainTest {
    /**
     * 普通数据测试 1000
     *  java 21 新特性 虚拟线程
     *
     */
    @Test
    public void VirtualThreadMain( ){
        long time1 = new Date().getTime();
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 1000; i++) {
                int finalI = i;
                executor.submit(() -> {
                    System.out.println("任务 " + finalI +" 运行在 " + Thread.currentThread());
                    TimeUnit.SECONDS.sleep(3);//模拟阻塞
                    // 执行其他操作
                    return "ok";
                });
            }
        }
        long time2 = new Date().getTime();
        System.out.println("耗时: "+ (time2 - time1) + " ms");
        //1. 耗时: 3205 ms
        //2. 耗时: 3230 ms
        //3. 耗时: 3219 ms
        //4. 耗时: 3221 ms
        //5. 耗时: 3227 ms
        // 16102/5 = 3220.4 ms
        //
    }

    /**
     * 普通数据测试 1000
     * 普通线程
     */
    @Test
    public void ThreadMain(){
        long time1 = new Date().getTime();
        try (var executor = Executors.newCachedThreadPool()){
            for (int i = 0; i < 1000; i++) {
                int finalI = i;
                executor.submit(() -> {
                    System.out.println("任务 " + finalI +" 运行在 " + Thread.currentThread());
                    TimeUnit.SECONDS.sleep(3);//模拟阻塞
                    // 执行其他操作
                    return "ok";
                });
            }
        }

        long time2 = new Date().getTime();
        System.out.println("耗时: "+ (time2 - time1) + " ms");
        //1. 耗时: 3466 ms
        //2. 耗时: 3377 ms
        //3. 耗时: 3433 ms
        //4. 耗时: 3478 ms
        //5. 耗时: 3434 ms
        //17188/5 =3437.6 ms
    }

    /**
     * 大数量测试
     * 普通 固定线程
     */
    @Test
    public void FixedThreadMain(){
        long time1 = new Date().getTime();
        try (var executor = Executors.newFixedThreadPool(18000)) {
            for (int i = 0; i < 100000; i++) {
                executor.submit(() -> {
                    TimeUnit.SECONDS.sleep(3);//模拟阻塞
                    // 执行其他操作
                    return "ok";
                });
            }
        }

        long time2 = new Date().getTime();
        System.out.println("Thread 耗时: "+ (time2 - time1) + " ms");

        long VirtualTime1 = new Date().getTime();
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 100000; i++) {
                executor.submit(() -> {
                    TimeUnit.SECONDS.sleep(3);//模拟阻塞
                    // 执行其他操作
                    return "ok";
                });
            }
        }
        long VirtualTime2 = new Date().getTime();
        System.out.println("VirtualThread 耗时: "+ (VirtualTime2 - VirtualTime1) + " ms");
    }
}
